package com.yz.service.impl;

import com.yz.constatns.RedisKey;
import com.yz.vo.LikeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

@Service
public class LikeService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    // 实现点赞
    public void clickLike(LikeVo likeVo) {

        // 1.准备点赞的key
        String likeKey = String.format(RedisKey.LIKE_KEY, likeVo.getEntityType(), likeVo.getEntityId());
        String userKey = String.format(RedisKey.USER_LIKE_NUM_KEY, likeVo.getEntityUserId());

        // 2.判断用户是否对该实体类id已经点赞了
        SetOperations<String, String> setOperations = stringRedisTemplate.opsForSet(); // set类型
        ValueOperations<String, String> valueOperations = stringRedisTemplate.opsForValue();
        Boolean member = setOperations.isMember(likeKey, likeVo.getUserId().toString());

        if (member) {
            // 该用户已经点赞了，取消点赞
            setOperations.remove(likeKey, likeVo.getUserId().toString());
            // 给实体对应作者的赞数减1
            valueOperations.decrement(userKey);
        } else {
            // 3.不在就实现点赞
            setOperations.add(likeKey, likeVo.getUserId().toString());
            // 给实体对应作者的赞数加1
            valueOperations.increment(userKey);
        }
    }

    public Long getInvitataionLikeCount(Integer type, Integer id) {
        String key = String.format(RedisKey.LIKE_KEY, type, id);
        return stringRedisTemplate.opsForSet().size(key);
    }

    public Boolean getInvitataionUserLike(Integer type, Integer userId, Integer intataionId) {
        String key = String.format(RedisKey.LIKE_KEY, type, intataionId);
        return stringRedisTemplate.opsForSet().isMember(key, userId.toString());
    }

    public Boolean isLike(LikeVo likeVo) {
        String key = String.format(RedisKey.LIKE_KEY, likeVo.getEntityType(), likeVo.getEntityId());
        return stringRedisTemplate.opsForSet().isMember(key, likeVo.getUserId().toString());
    }

    public Long getUserLikeCount(Integer id) {
        String key = String.format(RedisKey.USER_LIKE_NUM_KEY, id);
        String s = stringRedisTemplate.opsForValue().get(key);
        if (ObjectUtils.isEmpty(s)) {
            return 0L;
        }
        return Long.parseLong(s);
    }
}
